import re

from django.conf import settings
from django.core.mail import send_mail
from django_redis import get_redis_connection
from rest_framework import serializers
from itsdangerous import TimedJSONWebSignatureSerializer as TJS
from users.models import User
from rest_framework_jwt.settings import api_settings


class UserSerializers(serializers.ModelSerializer):
    # 显示指明模型类中没有的字段
    password2 = serializers.CharField(max_length=20, min_length=8, write_only=True)
    sms_code = serializers.CharField(max_length=6, min_length=6, write_only=True)
    # 字符串形式的 true 或 false
    allow = serializers.CharField(write_only=True)

    token = serializers.CharField(read_only=True)

    class Meta:
        model = User
        fields = ('username', 'password', 'password2', 'mobile', 'allow', 'sms_code', 'id', 'token')
        extra_kwargs = {
            'password':
                {
                    'max_length': 20,
                    'min_length': 8,
                    'write_only': True
                },
            'username':
                {
                    'max_length': 20,
                    'min_length': 5,
                }
        }

    def validate_mobile(self, value):
        if not re.match(r'^1[3-9]\d{9}$', value):
            raise serializers.ValidationError('手机格式不匹配')
        return value

    def validate_allow(self, value):
        if value != 'true':
            raise serializers.ValidationError('协议未同意')

    def validate(self, attrs):
        if attrs['password'] != attrs['password2']:
            raise serializers.ValidationError('两次密码不一致')
        # 判断用户名是否为手机格式
        if not re.match(r'1[3-9]\d{9}$', attrs['username']):
            if attrs['username'] != attrs['mobile']:
                raise serializers.ValidationError('用户名和手机号不一致')
        # 获取缓存中的短信验证码
        conn = get_redis_connection('sms_code')
        real_sms_code = conn.get('sms_code_%s' % attrs['mobile'])
        # 判断短信是否失效
        if real_sms_code is None:
            raise serializers.ValidationError('短信验证码已失效')
        if attrs['sms_code'] != real_sms_code.decode():
            raise serializers.ValidationError('输入短信验证码错误')
        return attrs

    # 保存
    def create(self, validated_data):
        # del validated_data['password2']
        # del validated_data['sms_code']
        # del validated_data['allow']
        # print(validated_data)
        # user = User.objects.create_user(validated_data)
        # return user
        del validated_data['password2']
        del validated_data['sms_code']
        del validated_data['allow']
        print(validated_data)
        #
        # user=User.objects.create_user(validated_data)

        user = User.objects.create_user(username=validated_data['username'], password=validated_data['password'],
                                        mobile=validated_data['mobile'])

        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        user.token = token
        return user


class UserShowSerialiszers(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('username', 'mobile', 'email', 'id', 'email_active')


class UserEmailSerialiszers(serializers.Serializer):
    # 验证
    email = serializers.EmailField()

    # 更新
    def update(self, instance, validated_data):
        # 加密用户信息
        tjs = TJS(settings.SECRET_KEY, 300)
        token = tjs.dumps({'username': instance.username}).decode()

        # verify_url = 'http://www.meiduo.site:8080/success_verify_email.html?token=' + token
        # # 收件人
        # to_email = validated_data['email']
        # subject = "梅朵邮箱验证"
        # html_message = '<p>尊敬的用户您好！</p>' \
        #                '<p>感谢您使用美多商城。</p>' \
        #                '<p>您的邮箱为：%s 。请点击此链接激活您的邮箱：</p>' \
        #                '<p><a href="%s">%s<a></p>' % (to_email, verify_url, verify_url)
        # # html_message = '<a href="www.baidu.com">百度</a> '
        # # 发送邮件
        # send_mail(subject, '验证信息', settings.EMAIL_FROM, [to_email], html_message=html_message)
        to_email = validated_data['email']
        send_mail.delay(token,to_email)
        instance.email = validated_data['email']
        instance.save()
        return instance
